﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TekaMUD.Engine.Behaviour;
using TekaMUD.Engine.Framework;

namespace TekaMUD.Engine.Blocks
{
	/// <summary>
	/// A type of room object from wich a specific NPC agent is spawned.
	/// </summary>
	public class SpawnPoint<T> : AbstractSpawnPoint where T : NPC, new()
	{
		public T Agent { get; private set; }
		public Room StartRoom { get; private set; }
		public TimeSpan Periodicity { get; private set; }
		public DateTime LastActivation { get; private set; }
		public Guid ID { get; private set; }
		public Guid? NPC_ID;

		public SpawnPoint(Room startRoom, TimeSpan periodicity)
		{
			StartRoom = startRoom;
			Periodicity = periodicity;
			ID = Guid.NewGuid();
		}

		/// <summary>
		/// Creates a new NPC and puts it into the world.
		/// </summary>
		public override void Activate()
		{
			Activate(false);
		}

		/// <summary>
		/// Creates a new NPC and puts it into the world.
		/// </summary>
		public override void Activate(bool force)
		{
			Logger.LogDebug("Spawn point " + ID.ToString("D") + " activating.");
			NPC npc;

			if (NPC_ID != null)
			{
				npc = EntityManager.GetNPCByID(NPC_ID.Value);

				// Do nothing if the NPC still exists.
				if (npc != null && !force)
					return;
			}

			Logger.LogDebug("Creating new agent of type: " + typeof(T).Name);

			// Create a new NPC from the type given.
			T agent = new T() { Channel = null, CurrentRoom = StartRoom, SpawnTime = DateTime.Now };

			// Register in the game entity manager.
			EntityManager.RegisterInstance(agent);

			NPC_ID = agent.UID;

			agent.Activate();
			LastActivation = agent.SpawnTime;
		}
	}
}
